//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.wsd.smartcarwasher.service;

import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.dao.PartnerConfigMapper;
import com.wsd.smartcarwasher.dao.PartnerDao;
import com.wsd.smartcarwasher.domain.Machine;
import com.wsd.smartcarwasher.domain.Partner;
import com.wsd.smartcarwasher.domain.PartnerConfig;
import com.wsd.smartcarwasher.domain.PartnerConfigExample;
import com.wsd.smartcarwasher.util.ReturnUtil;
//import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PartnerService {
    Logger logger = LoggerFactory.getLogger(PartnerService.class);
    @Resource
    private PartnerDao partnerDao;
    @Resource
    private MachineService machineService;
    @Resource
    private StoreService storeService;

    @Resource
    private PartnerConfigMapper partnerConfigMapper;

    public PartnerService() {
    }

    @Transactional
    public int addPartner(Partner partner) {

        int changeRows = this.partnerDao.addPartner(partner);
        if (partner.getMachines().size()>0) {
            this.machineService.setMachinePartnerIdById(partner.getId(), partner.getMachines());
        }
        return changeRows;
    }

    public List<Partner> getDataerParList(String id)
    {
        return  this.partnerDao.queryDataPartner(id);
    }


    public Map<String,String> getPartnerByCellphone(String cellphone)
    {
        Partner partner=this.partnerDao.getPartnerByPhoneNumber(cellphone);
        Map<String,String> map=new HashMap<>();
//        map.put("realname",partner.getRealname());
        map.put("partnerId",partner.getId().toString());
        PartnerConfigExample partnerConfigExample=new PartnerConfigExample();
        partnerConfigExample.createCriteria().andPartnerIdEqualTo(partner.getId());
        List<PartnerConfig> partnerConfigList=this.partnerConfigMapper.selectByExample(partnerConfigExample);
        map.put("name",partner.getRealname()==null?partner.getRealname():partnerConfigList.get(0).getName());
        return map;
    }

//    private void passwordEncryption(Partner partner) {
//        String salt = String.valueOf(System.currentTimeMillis());
//        partner.setSalt(salt);
//        String password = (new SimpleHash("MD5", partner.getPassword(), partner.getSalt(), 2)).toString();
//        partner.setPassword(password);
//    }
    public int updatePartner(Partner partner) {
        int changeRow = 0;
        if (partner.getRealname() != null || partner.getCellphone() != null || partner.getAuthcode() != null || partner.getPassword() != null || partner.getAddition() != null || partner.getAccount() != null || partner.getProfit() != null || partner.getBankcard() != null || partner.getOpenId() != null) {
            changeRow = this.partnerDao.updatePartner(partner);
        }

        if (StringUtils.isNotBlank(partner.getMachineName())) {
            this.machineService.removeMachineOfPartner(partner.getId());
            //changeRow = this.machineService.setMachinePartnerId(partner.getId(), Arrays.asList(partner.getMachineName().split(",")));
            this.machineService.setMachinePartnerIdById(partner.getId(), partner.getMachines());
        }

        return changeRow;
    }

    private void passwordEncryption(Partner partner) {
        String salt = System.currentTimeMillis() + "";
        partner.setSalt(salt);
        String password = (new SimpleHash("MD5", partner.getPassword(), partner.getSalt(), 2)).toString();
        partner.setPassword(password);
    }
    private String passwordEncryptionBySalt(String password,String salt) {
        return new SimpleHash("MD5", password, salt, 2).toString();
    }
    public boolean hasPartnerWithCellphone(String cellphone) {
        return this.partnerDao.hasPartnerWithCellphone(cellphone) != null;
    }
    public List<Partner> queryAllPartner() {
        List<Partner> partners = this.partnerDao.queryAllPartner();
        return partners == null ? Collections.emptyList() : partners;
    }
    public Partner getPartnerByOpenId(String openId) {
        Partner partner = this.partnerDao.getPartnerByOpenId(openId);
        this.changeShowBankcard(partner);
        return partner;
    }

    public Partner getPartnerWithCardNumByOpenId(String openId) {
        return this.partnerDao.getPartnerByOpenId(openId);
    }

    private void changeShowBankcard(Partner partner) {
        if (partner != null && !StringUtils.isBlank(partner.getBankcard())) {
            String backcard = partner.getBankcard();
            partner.setBankcard(backcard.substring(0, 4) + this.getStar(backcard.length() - 8) + backcard.substring(backcard.length() - 4));
        }
    }
    private String getStar(int length) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < length; ++i) {
            sb.append("*");
        }

        return sb.toString();
    }


    public ModelMap relatePartner(String openId, String cellphone, String password) {
        this.logger.info("cellphone= " + cellphone);
        //表里对应的商家端
        Partner partner = this.getPartnerByPhoneNumber(cellphone);
        this.logger.info("partner is null: " + (partner == null));

//        String pwd=this.passwordEncryptionBySalt(password,partner.getSalt());
        if (partner != null && password.equals(partner.getPassword())) {
            if (StringUtils.isNotBlank(partner.getOpenId())) {
                return ReturnUtil.Error(ResultState.PARTNER_BEEN_BIND.getMsg());
            } else {
                int changeRow = this.partnerDao.setOpenIdOfPartner(partner.getId(), openId);
                if (changeRow == 0) {
                    return ReturnUtil.Error(ResultState.PARTNER_BIND_FAIL.getMsg());
                } else {
                    partner.setOpenId(openId);
                    partner.setMachines(this.machineService.getMachinesByPartnerId(partner.getId()));
                    this.changeShowBankcard(partner);
                    return ReturnUtil.Success(ResultState.PARTNER_BIND_SUCCESS.getMsg(), partner);
                }
            }
        } else {
            return ReturnUtil.Error(ResultState.WRONG_PHONE_NUMBER_OR_PASSWORD.getMsg());
        }
    }

    private Partner getPartnerByPhoneNumber(String cellphone) {
        return this.partnerDao.getPartnerByPhoneNumber(cellphone);
    }

    public Partner getPartnerById(int id) {
        return this.partnerDao.getPartnerById(id);
    }

    public int deletePartnerId(int partnerId) {
        return this.partnerDao.deletePartner(partnerId);
    }

    public int changePartnerAccountAndProfit(BigDecimal account, BigDecimal profit, int partnerId) {
        return this.partnerDao.changePartnerAccountAndProfit(account, profit, partnerId);
    }
    //获取所有加盟商
    public List<Partner> queryAllPartnerCount() {

        List<Partner>  ls = this.partnerDao.queryAllPartnerCount();
        ls.forEach(partner -> {
            partner.setMachines(this.machineService.getMachinesByPartnerId(partner.getId()));
            partner.setStores(this.storeService.getPartnerList(partner.getId()));
        });
        return ls;
    }
    //获取加盟商下的所有设备
    public List<Machine> getMachines(Integer id) {
        return this.machineService.getMachinesByPartnerId(id);
    }
    //商家登录
    public ModelMap loginByPassword(String name, String cellphone, String password, HttpServletRequest request) {
        Partner partner=this.partnerDao.getPartnerByCellphone(cellphone);
        password=this.passwordEncryptionBySalt(password,partner.getSalt());
        //根据加盟商查配额id
        if(!name.equals(partner.getUsername()))
        {
            PartnerConfigExample example=new PartnerConfigExample();
            example.createCriteria().andPartnerIdEqualTo(partner.getId())
                    .andStatusEqualTo((byte)0);
            List<PartnerConfig> partnerConfigList=this.partnerConfigMapper.selectByExample(example);
            if(partnerConfigList.isEmpty())
            {
                return ReturnUtil.Error("不存在登录名");
            }
            if(name.equals(partnerConfigList.get(0).getName()))
            {
                if(password.equals(partner.getPassword()))
                {
                    request.getSession().setAttribute("cellphone",cellphone);
                    request.getSession().setAttribute("username",name);
                    return ReturnUtil.Success("登陆成功");
                }
                return ReturnUtil.Error("登录名错误");
            }
            return ReturnUtil.Error("登录名错误");
        }else{
            if(password.equals(partner.getPassword()))
            {
                request.getSession().setAttribute("cellphone",cellphone);
                request.getSession().setAttribute("username",name);
                return ReturnUtil.Success("登陆成功");
            }
            System.out.println("error");
            return ReturnUtil.Error("登录名错误");
        }
    }
            public  int delPartnerOpenId(Integer partnerId)
            {
                return  this.partnerDao.setOpenIdOfPartner(partnerId,null);
            }
}

/*
package com.wsd.smartcarwasher.service;

import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.dao.PartnerDao;
import com.wsd.smartcarwasher.domain.Partner;
import com.wsd.smartcarwasher.util.ReturnUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Service
public class PartnerService {
    Logger logger = LoggerFactory.getLogger(PartnerService.class);

    @Resource
    private PartnerDao partnerDao;

    @Resource
    private MachineService machineService;

    @Transactional
    public int addPartner(Partner partner) {
        //passwordEncryption(partner);
        int changeRows = partnerDao.addPartner(partner);
        if (changeRows == 1 && StringUtils.isNotBlank(partner.getMachineName())) {
            machineService.setMachinePartnerId(partner.getId(), Arrays.asList(partner.getMachineName().split(",")));
        }
        return changeRows;
    }

    public int updatePartner(Partner partner) {
//        if (StringUtils.isNotBlank(partner.getPassword())) {
//            partner.setPassword(new SimpleHash(Global.HASH_ALGORITHM_NAME, partner.getPassword(), partner.getSalt(), Global.HASH_ITERATIONS).toString());
//        }
        return partnerDao.updatePartner(partner);
    }

    private void passwordEncryption(Partner partner) {
        String salt = System.currentTimeMillis() + "";
        partner.setSalt(salt);
        //加密密码
        String password = new SimpleHash(Global.HASH_ALGORITHM_NAME, partner.getPassword(), partner.getSalt(), Global.HASH_ITERATIONS).toString();
        partner.setPassword(password);
    }

    public boolean hasPartnerWithCellphone(String cellphone) {
        return partnerDao.hasPartnerWithCellphone(cellphone) != null;
    }

    public List<Partner> queryAllPartner() {
        List<Partner> partners = partnerDao.queryAllPartner();
        if (partners == null) {
            return Collections.emptyList();
        }
        return partners;
    }

    public Partner getPartnerByOpenId(String openId) {
        Partner partner = partnerDao.getPartnerByOpenId(openId);
        changeShowBankcard(partner);
        return partner;
    }

    */
/**
     * 查询银行卡号没有经过特殊处理的运营商信息
     *
     * @param openId 运营商openId
     * @return 运营商信息
     *//*

    public Partner getPartnerWithCardNumByOpenId(String openId) {
        return partnerDao.getPartnerByOpenId(openId);
    }

    private void changeShowBankcard(Partner partner) {
        if (partner == null || StringUtils.isBlank(partner.getBankcard())) {
            return;
        }
        String backcard = partner.getBankcard();
        partner.setBankcard(backcard.substring(0, 4) + getStar(backcard.length() - 8) + backcard.substring(backcard.length() - 4));
    }

    private String getStar(int length) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append("*");
        }
        return sb.toString();
    }

    public ModelMap relatePartner(String openId, String cellphone, String password) {
        logger.info("cellphone= " + cellphone);
        Partner partner = getPartnerByPhoneNumber(cellphone);
        logger.info("partner is null: " + (partner == null));
        //String passwordMd5 = new SimpleHash(Global.HASH_ALGORITHM_NAME, password, partner.getSalt(), Global.HASH_ITERATIONS).toString();
        if (partner == null || !password.equals(partner.getPassword())) {
            return ReturnUtil.Error(ResultState.WRONG_PHONE_NUMBER_OR_PASSWORD.getMsg());
        }
        if (StringUtils.isNotBlank(partner.getOpenId())) {
            return ReturnUtil.Error(ResultState.PARTNER_BEEN_BIND.getMsg());
        }
        int changeRow = partnerDao.setOpenIdOfPartner(partner.getId(), openId);
        if (changeRow == 0) {
            return ReturnUtil.Error(ResultState.PARTNER_BIND_FAIL.getMsg());
        }
        partner.setOpenId(openId);
        partner.setMachines(machineService.getMachinesByPartnerId(partner.getId()));
        changeShowBankcard(partner);
        return ReturnUtil.Success(ResultState.PARTNER_BIND_SUCCESS.getMsg(), partner);
    }

    private Partner getPartnerByPhoneNumber(String cellphone) {
        return partnerDao.getPartnerByPhoneNumber(cellphone);
    }

    public Partner getPartnerById(int id) {
        return partnerDao.getPartnerById(id);
    }

    public int deletePartnerId(int partnerId) {
        return partnerDao.deletePartner(partnerId);
    }

    public int changePartnerAccountAndProfit(BigDecimal account, BigDecimal profit, int partnerId) {
        return partnerDao.changePartnerAccountAndProfit(account, profit, partnerId);
    }
}
*/
